<template>
  <div>
    <!--search and add department-->
    <div class="header">
      <div class="search">
        <input
          v-model="keyword"
          class="search-input icon"
          type="search"
          :placeholder="search"
        />
      </div>
      <div class="coverSearch" v-show="showCoverKeyword">
        {{ coverKeyword }}
      </div>
      <el-button class="button" plain @click="handleOpenAdd"
        >添加部门</el-button
      >
    </div>
    <!--department card-->
    <div
      class="room-card shadow"
      v-for="(item, index) of list"
      :key="index"
      v-show="showCard(item)"
    >
      <img
        class="room-img"
        :src="item.image || '../../../static/img/department.jpg'"
        width="300"
      />
      <div class="room-name">{{ item.departmentName }}</div>
      <div class="button-member" @click="handleMemberClick(item)">成员</div>
      <div class="button-info" @click="handleInfoClick(item)">信息</div>
    </div>
    <!--department information-->
    <el-dialog
      :title="this.dialogTitle"
      :visible.sync="showInfo"
      @close="handleInfoClose"
      width="400px"
      center
    >
      <img
        :src="this.department.image || '../../../static/img/department.jpg'"
        width="100%"
        height="250px"
        style="margin-top: -20px"
      />
      <ul class="room-info" v-show="alter">
        <li>
          <strong>部门名称:</strong
          ><span>{{ this.department.departmentName }}</span>
        </li>
        <li>
          <strong>部门简介:</strong
          ><span>{{
            this.department.introduction === null
              ? "暂无"
              : this.department.introduction
          }}</span>
        </li>
        <li>
          <strong>管&nbsp;&nbsp;理&nbsp;&nbsp;员:</strong
          ><span class="info-admin"
            ><el-tag
              type="danger"
              :key="index"
              v-for="(item, index) of this.admin"
              >{{ item.label }}</el-tag
            ></span
          >
        </li>
      </ul>
      <ul class="room-info" v-show="!alter">
        <li>
          <strong>部门名称：</strong
          ><el-input
            class="alter-input sj"
            v-model="department.departmentName"
            type="text"
          ></el-input>
        </li>
        <li>
          <strong>部门简介:</strong
          ><el-input
            class="alter-input"
            v-model="department.introduction"
            type="text"
          ></el-input>
        </li>
        <li>
          <strong>管&nbsp;&nbsp;理&nbsp;&nbsp;员:</strong
          ><el-select v-model="department.admin" class="alter-select" multiple>
            <el-option
              v-for="item in this.setAdmin"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </li>
      </ul>
      <span slot="footer" class="dialog-footer">
        <el-button v-show="alter" plain @click="handleAlter">修改</el-button>
        <el-button v-show="alter" type="primary" @click="handleDeleteClick"
          >删除</el-button
        >
        <el-button v-show="!alter" plain @click="handleSaveClick"
          >保存</el-button
        >
        <el-button v-show="!alter" type="primary" @click="handleCancel"
          >取消</el-button
        >
      </span>
    </el-dialog>
    <!--add department-->
    <el-dialog
      title="添加部门"
      :visible.sync="showAdd"
      @close="handleAddClose"
      width="400px"
      center
    >
      <ul class="room-info">
        <li>
          <strong>部门名称：</strong
          ><el-input
            v-model="form.departmentName"
            class="alter-input sj"
            type="text"
          />
        </li>
        <li>
          <strong>部门简介:</strong
          ><el-input
            v-model="form.introduction"
            class="alter-input"
            type="text"
          />
        </li>
        <li>
          <strong>管&nbsp;&nbsp;理&nbsp;&nbsp;员:</strong
          ><el-select
            v-model="form.admin"
            class="alter-select"
            type="text"
            multiple
          >
            <el-option
              v-for="item in this.setAdmin"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </li>
      </ul>
      <span slot="footer" class="dialog-footer">
        <el-button plain @click="handleAddDepartment">提交</el-button>
        <el-button type="primary" @click="showAdd = false">取消</el-button>
      </span>
    </el-dialog>
    <!--department member-->
    <el-dialog title="部门成员" :visible.sync="showMember" width="400px" center>
      <div class="member-search">
        <input
          class="member-search-input icon"
          v-model="memberKeyword"
          type="search"
          :placeholder="iconsearch"
        />
      </div>
      <ul class="member-list">
        <li
          class="member-item"
          v-for="(item, index) of memberItemList"
          :key="index"
        >
          <span>{{ index + 1 }}</span>
          <span class="member-phone">{{ item.phoneNum || "无号码" }}</span>
          <span class="member-name">{{ item.name || "匿名" }}</span>
          <span class="member-admin">{{
            isAdmin(item) === true ? "管理员" : ""
          }}</span>
        </li>
        <li class="no-member" v-show="showNoMember">无成员</li>
      </ul>
    </el-dialog>
  </div>
</template>

<script>
import axios from "axios";
import ElOption from "element-ui/packages/select/src/option";

export default {
  components: { ElOption },
  inject: ["reload"],
  name: "DepartmentList",
  props: {
    list: Array
  },
  data() {
    return {
      keyword: "",
      memberKeyword: "",
      search: "\ue693输入部门/成员名称",
      iconsearch: "\ue693输入成员名称",
      showCoverKeyword: false,
      coverKeyword: "",
      hasMember: true,
      showMember: false,
      showNoMember: false,
      showInfo: false,
      showAdd: false,
      alter: true,
      dialogImageUrl: "",
      dialogVisible: false,
      dialogTitle: "",
      department: [],
      member: [],
      admin: [],
      departmentAdmin: [],
      memberList: [],
      memberItemList: [],
      form: {
        departmentName: "",
        introduction: "",
        admin: []
      },
      setAdmin: [],
      allUser: [
        {
          id: 34,
          name: "测试用户1"
        },
        {
          id: 37,
          name: "测试用户2"
        },
        {
          id: 38,
          name: "测试用户3"
        },
        {
          id: 54,
          name: "测试用户4"
        }
      ]
    };
  },
  methods: {
    // 展示部门卡片
    showCard: function(item) {
      return (
        this.keyword === "" ||
        item.departmentName.indexOf(this.keyword) > -1 ||
        this.hasMember
      );
    },
    // 打开成员信息
    handleMemberClick: function(item) {
      this.showNoMember = false;
      this.department = item;
      this.showMember = !this.showMember;
      this.getMemberInfo();
    },
    // 打开部门信息
    handleInfoClick: function(item) {
      const _this = this;
      this.dialogTitle = "部门信息";
      this.alter = true;
      this.showInfo = true;
      this.department = item;
      if (item.admin) {
        for (let i = 0; i < item.admin.length; i++) {
          axios
            .get("http://119.23.110.183:8080/getUserinfo?id=" + item.admin[i])
            .then(function(res) {
              res = res.data;
              if (res.code === 0) {
                const data = res.data.userinfo;
                if (data.name === null) {
                  data.name = "匿名";
                }
                _this.admin.push({
                  value: data.id,
                  label: data.name
                });
              }
            });
        }
      } else {
        this.admin.push({ label: "暂无", value: -1 });
      }
      this.department.admin = [];
    },
    // 关闭部门信息
    handleInfoClose: function() {
      this.admin = [];
      this.department.admin = [];
      this.setAdmin = [];
      this.reload();
    },
    // 预览上传图片
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    // 检查图片大小
    beforeAvatarUpload(file) {
      const isLt5M = file.size / 1024 / 1024 < 5;
      if (!isLt5M) {
        this.$message.error("上传头像图片大小不能超过 5M!");
      }
      return isLt5M;
    },
    // 图片超过上限
    exceedFile() {
      this.$message.error("上传图片数达到上限!");
    },
    // 图片上传成功
    imgSuccess(res) {
      // res = res.data
      if (res.code === 0) {
        const data = res.data;
        this.$message({
          message: "图片上传成功",
          type: "success"
        });
        this.dialogImageUrl = data.path;
      } else {
        this.$message.error("图片上传失败");
      }
    },
    handleAlter: function() {
      this.setAdmin = this.allUser;
      this.alter = false;
      this.dialogTitle = "修改部门信息";
    },
    handleCancel: function() {
      this.alter = true;
      this.dialogTitle = "部门信息";
      this.form.admin = [];
      this.admin = [];
      this.setAdmin = [];
    },
    // 保存修改后的部门信息
    handleSaveClick: function() {
      this.alter = true;
      const _this = this;
      this.department.image = this.dialogImageUrl;
      this.department.admin = "36-37-38";
      axios.defaults.headers.common["Authorization"] = this.$store.state.token;
      console.log('department', this.department)
      axios
        .post("http://119.23.110.183:8080/alterDepartment", this.department)
        .then(function(res) {
          console.log(res)
          res = res.data;
          if (res.code === 0) {
            _this.$message({
              message: "保存成功",
              type: "success"
            });
          }
        }).catch(err => {
          console.log(err)
      })
      this.dialogImageUrl = "";
      // this.reload()
    },
    // 删除部门
    handleDeleteClick: function() {
      const _this = this;
      this.$confirm("确认删除?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          axios.defaults.headers.common[
            "Authorization"
          ] = this.$store.state.token;
          axios
            .get(
              "http://119.23.110.183:8080/deleteDepartment?did=" +
                this.department.departmentId
            )
            .then(function(res) {
              res = res.data;
              if (res.code === 0) {
                _this.$message({
                  message: "删除成功",
                  type: "success"
                });
                _this.roomInfoVisible = false;
                _this.reload();
              } else {
                _this.$message.error("删除失败，" + res.msg);
              }
            });
        })
        .catch(() => {});
    },
    // 添加部门
    handleAddDepartment: function() {
      const _this = this;
      this.form.admin = this.form.admin.join("-");
      axios
        .post(
          "http://119.23.110.183:8080/insertDepartment?admin=" +
            this.form.admin +
            "&departmentName=" +
            this.form.departmentName +
            "&introduction=" +
            this.form.introduction
        )
        .then(function(res) {
          res = res.data;
          if (res.code === 0) {
            _this.$message({
              message: "添加部门成功",
              type: "success"
            });
            _this.reload();
          } else {
            _this.$message.error(res.msg);
          }
        });
      this.showAdd = false;
      this.form.admin = [];
    },
    handleOpenAdd: function() {
      this.setAdmin = this.allUser;
      this.showAdd = true;
    },
    // 获取部门成员信息
    getMemberInfo: function() {
      const _this = this;
      axios.defaults.headers.common["Authorization"] = this.$store.state.token;
      axios
        .get(
          "http://119.23.110.183:8080/getAllUserInfoByDid?did=" +
            _this.department.departmentId
        )
        .then(function(res) {
          res = res.data;
          if (res.code === 0) {
            const data = res.data;
            if (data.admin !== null) {
              _this.departmentAdmin = data.admin.split("-");
            }
            if (data.list == false) {
              _this.showNoMember = true;
            }

            _this.memberItemList = data.list;
            _this.memberList = data.list;
          }
        });
    },
    // 判断是否为管理员
    isAdmin: function(item) {
      const _this = this;
      for (let i = 0; i < _this.departmentAdmin.length; i++) {
        if (item.id == _this.departmentAdmin[i]) {
          return true;
        }
      }
      return false;
    },
    handleAddClose: function() {
      this.showAdd = false;
      this.form.departmentName = "";
      this.form.introduction = "";
      this.form.admin = [];
      this.setAdmin = [];
      // this.reload()
    }
  },
  watch: {
    // 搜索成员
    memberKeyword: function() {
      const memberkeyword = this.memberKeyword;
      const list = this.memberList;
      const itemList = [];
      if (this.memberkeyword === "") {
        this.memberItemList = list;
        this.showNoMember = false;
      } else {
        for (let i = 0; i < list.length; i++) {
          if (list[i].name !== null) {
            if (list[i].phoneNum === null) {
              itemList.push(list[i]);
            } else {
              if (
                list[i].name.indexOf(memberkeyword) > -1 ||
                list[i].phoneNum.indexOf(memberkeyword) > -1
              ) {
                itemList.push(list[i]);
              }
            }
          } else {
            itemList.push(list[i]);
          }
        }
        if (itemList.length === 0) {
          this.showNoMember = true;
        } else {
          this.showNoMember = false;
        }
        this.memberItemList = itemList;
      }
    },
    // 搜索部门
    keyword: function() {
      const _this = this;
      const list = this.memberList;
      this.hasMember = false;
      if (this.keyword !== "") {
        for (let i = 0; i < list.length; i++) {
          if (list[i].name !== null) {
            if (list[i].name.indexOf(this.keyword) > -1) {
              _this.hasMember = true;
            }
          }
          if (this.keyword !== "") {
            for (let i = 0; i < _this.allUser.length; i++) {
              if (_this.allUser[i].name !== null) {
                // console.log('this.keyword=', this.keyword, ',allUser[' + i + '].name=', _this.allUser[i].name,_this.allUser[i].name.indexOf(this.keyword) > -1)
                if (_this.allUser[i].name.indexOf(this.keyword) > -1) {
                  this.showCoverKeyword = true;
                  this.coverKeyword = this.keyword;
                  this.keyword = "后台开发部";
                }
              }
            }
          }
        }
      }
      if (this.keyword === "") {
        this.showCoverKeyword = false;
        _this.hasMember = true;
        _this.showNoMember = false;
      }
    }
  }
};
</script>

<style lang="stylus" scoped>
.coverSearch{
  width 200px
  height 40px
  background #fff
  position absolute
  top 100px
  left 120px
  border-radius 0.06rem
  line-height 40px
  color #888
  padding-left 10px
}
.header
  float left
  width 100%
  margin-top 10px
.search
  float: left
  margin-left 15px
  padding 0 .1rem
.search-input
  float: left
  box-sizing border-box
  height 40px
  width 250px
  font-size 14px
  padding: 0 .1rem
  line-height: 40px
  border-radius .06rem
  color: #888
  outline 0
  border: 1px solid #DCDFE6
.button
  float left
  margin-left 15px

.room-card
  float left
  margin 20px
  margin-right: 10px
  width: 300px
  height: 240px
  padding: 0
  background-color: #fff
  border-radius 5px
  transition: all .2s
.room-card:hover
//  box-shadow 2px 2px 20px rgba(0, 0, 0, .1)
  transform scale(1.005)
.room-img
  height 200px
  width 100%
  border-radius 5px 5px 0 0
.room-name
  font-size: 16px;
  color: #333;
  height: 20px;
  line-height: 20px;
  float: left;
  margin-left: 20px;
  margin-top: 10px;
.room-desc
  margin-top: 10px
  background-color: #ffffff
.button-info,
.button-member
  float: right;
  width: 50px;
  height: 25px;
  cursor: pointer;
  line-height: 25px;
  text-align: center;
  border-radius: 2px;
  margin: 10px;
  color: #ffffff;
  font-size: 12px;
.button-info
  background-color: orange;
  margin-top: 8px;
.button-member
  background-color: green;
  margin-right 20px;
  margin-top: 8px;
.button-info:hover
  background #e6a23c
.button-member:hover
  background #67c23a
.room-info li
  margin-top 20px
.room-info li:not(last-child) span
  margin-left 20px
.room-info li:last-child span
  margin-left 6px
.dialog-footer
  margin-right -190px
.alter-select,
.alter-input
  width: 200px;
  height: 20px;
  line-height: 20px;
  margin-left: 20px;
.sj
  margin-left 12px
.alter-select {
  height: 60px;
  margin-left: 18px;
}
.member-search
   height 25px
   width 200px
   margin: 0 auto
   padding 0 .1rem
   .member-search-input
     float: left
     box-sizing border-box
     width 100%
     height: .5rem
     padding: 0 .1rem
     line-height: .5rem
     color: #888
     border 1px solid #cacaca
     border-radius: 20px
.member-list {
  width: 100%;
  margin: 0 auto;
  margin-left -20px
  padding: 20px;
}
.member-item {
  width: 350px;
  height: 28px;
  background: #e5e5e5;
  line-height: 28px;
  margin-bottom: 15px;
  padding-left: 10px;
  border-radius: 20px;
  cursor: pointer
}
.member-item:hover{
  color #fff
  background #d7341fa6
}
.member-item span
  display block
  float left
.member-phone
  width 100px
  margin-left 30px
.member-name
  width 100px
  margin-left 30px
.no-member
  width: 350px;
  height: 60px;
  background: #e5e5e5;
  line-height: 50px;
  margin 0 auto
  margin-bottom: 15px;
  padding-left: 10px;
  border-radius: 3px;
  text-align center
</style>
